<template>
    <div class="border border-br flex flex-col" :style="styles">
 

        <toolbar
            class="border-b border-br"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
        />
        <w-editor
            class="overflow-y-auto flex-1"
            v-model="valueHtml"
            :defaultConfig="editorConfig"
            :mode="mode" 
            @onCreated="handleCreated" 
        />
        
    </div>
</template>
<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css 
import { Editor as WEditor,Toolbar  } from '@wangeditor/editor-for-vue'  
import { addUnit } from '@/utils/util' 
import { useUserStore } from '@/stores/user'
 
const getToken = () => {
    const store = useUserStore()
    return store.token
}

const props = defineProps({
        modelValue: '',
        mode: 'default',
        height: '100%',
        width: 'auto',
        toolbarConfig: () => ({  })
}) 
const emits = defineEmits([
    'update:modelValue',
    'value', 
])

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
  
const editorConfig = {
    MENU_CONF: {
        uploadImage: {
            server: `${import.meta.env.VITE_APP_BASE_API}/file/upload`,
            fieldName: 'file',
            headers: {
                'Authorization': 'Bearer ' + getToken()
            },
            customInsert(res, insertFn) {        
                insertFn(res.data.url, res.data.name)
            } 
        }, 
        uploadVideo: {
            server: `${import.meta.env.VITE_APP_BASE_API}/file/upload`,
            fieldName: 'file',
            headers: {
                'Authorization': 'Bearer ' + getToken()
            },
            customInsert(res, insertFn) {        
                insertFn(res.data.url, res.data.name)
            } 
        }
    },
    excludeKeys:{

    }
}
 
const styles = computed(() => ({
    height: addUnit(props.height),
    width: addUnit(props.width)
}))
const valueHtml = computed({
    get() {
        return props.modelValue
    },
    set(value) {
        emits('update:modelValue', value)
    }
})
 

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}
</script>

<style lang="scss">
.w-e-full-screen-container {
    z-index: 999;
}
.w-e-text-container [data-slate-editor] ul {
    list-style: disc;
}
.w-e-text-container [data-slate-editor] ol {
    list-style: decimal;
}
h1 {
    font-size: 2em;
}
h2 {
    font-size: 1.5em;
}
h3 {
    font-size: 1.17em;
}
h4 {
    font-size: 1em;
}
h5 {
    font-size: 0.83em;
}
h1,
h2,
h3,
h4,
h5 {
    font-weight: bold;
}
</style>
